package gecko;

import gecko.lang.StringReader;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * GeckoClient 是一个提供
 *
 * @author 陈永佳 (yoojiachen@gmail.com)
 * @version 0.0.1
 */
public class GeckoClient {

    public static final int IPC_PORT = 5570;
    public static final int TCP_PORT = 5571;
    public static final int UDP_PORT = 5572;
    public static final int WEB_PORT = 5573;
    public static final String HOST = "127.0.0.1";

    private static final String BASE_URL = "http://" + GeckoClient.HOST + ":" + GeckoClient.IPC_PORT;

    public static String request(String topic, Headers headers, byte[] jsonBytes) throws IOException {
        final URL url = new URL(BASE_URL + topic);
        final HttpURLConnection http = (HttpURLConnection) url.openConnection();
        try {
            http.setDoOutput(true);
            http.setRequestMethod("POST");
            http.setRequestProperty("X-Client", "Gecko");
            http.setRequestProperty("Content-FrameType", "application/json");
            http.setFixedLengthStreamingMode(jsonBytes.length);
            http.setUseCaches(false);
            http.setDefaultUseCaches(false);

            headers.forEach(http::setRequestProperty);

            try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) {
                wr.write(jsonBytes);
            }
            return StringReader.read(http.getInputStream());
        } finally {
            http.disconnect();
        }

    }
}
